#include "uploadvideothread.h"
#include "commonfuc.h"
#include "logfile.h"
#include <QThread>
#include <QTextCodec>

uploadVideoThread::uploadVideoThread()
{
    QTextCodec::codecForName("utf-8");//GBK
    memset(accessKey,0,sizeof(accessKey));
    memset(secretKey,0,sizeof(secretKey));

    m_curFilePath = QString();
    m_uploadtoken = QString();
    m_nId = 0xFFFFFFFF;
}

uploadVideoThread::~uploadVideoThread()
{
    Qiniu_Client_Cleanup(&m_QinniuClient);  /* 每个HTTP客户端使用完后释放 */
}

void uploadVideoThread::onInitQiniu(quint64 id,TRANSFER_INFO info)
{
    //int nThreadId = (int)QThread::currentThreadId();
    paraInfo = info;
    m_nId = id;

    //qiniu init ...

    //梁淑超
    //m_QinniubucketName    = "dennyliang-huadong";
    //m_QinniuMac.accessKey = "gVvghqolv6y50M_Zrstas_h4k80pN5UgX2AyXdix";
    //m_QinniuMac.secretKey = "vBKFKQn7GTjtkLf1YqDjRQBw6ekyV3uQDBM1GB3X";
    //m_QinniuClient.nUpHostZone = 0;

    //生产环境
    //m_QinniubucketName = "video";
    //m_QinniuMac.accessKey = "63LAFMMKCMPxne0C1RafN-X1PvsKMNHghDM3cYSD";
    //m_QinniuMac.secretKey = "S0WhkmqcKkrX1G8WDV2rJJhVnTSKieaztR3xdDUX";
    //m_QinniuClient.nUpHostZone = 0;

    //0:华东；1：华北；2：华南；3：北美
    //m_QinniuClient.nUpHostZone = 0;

    /*std::string str = paraInfo.accessKey.toStdString();
    m_QinniuMac.accessKey = str.c_str();
    std::string str1 = paraInfo.secretkey.toStdString();
    m_QinniuMac.secretKey = str1.c_str();*/
    CommonFuc::GetCharByQString(paraInfo.accessKey,accessKey,256);
    CommonFuc::GetCharByQString(paraInfo.secretkey,secretKey,256);
    m_QinniuMac.accessKey = (const char*)accessKey;
    m_QinniuMac.secretKey = (const char*)secretKey;


#ifdef WIN32
    m_QinniuClient.nUpHostZone = paraInfo.qiniuZone;
#endif

    Qiniu_Client_InitNoAuth(&m_QinniuClient, 1024); /* HTTP客户端初始化。HTTP客户端是线程不安全的，不要在多个线程间共用 */
}

char* uploadVideoThread::upLoadToken(const char* bucket, Qiniu_Mac* mac)
{
    Qiniu_RS_PutPolicy putPolicy;
    Qiniu_Zero(putPolicy);

    putPolicy.scope = bucket;

    QString strTargetAddress;
    //strTargetAddress.sprintf("dennyliang-huadong:liangshuchao_test1_%d.mp4",mm);
    strTargetAddress.sprintf("%s:%s",paraInfo.transcodeBucket.toStdString().c_str(),m_fileName.toStdString().c_str());

    QString strTargetAddress_MD5 = CommonFuc::GetBase64Encode(strTargetAddress);


    //putPolicy.persistentOps = "avthumb/m3u8/noDomain/1/segtime/15/vb/440k";
    //putPolicy.persistentOps = "avthumb/mp4/ab/160k/ar/44100/acodec/libfaac/r/30/vb/2200k/vcodec/libx264/s/1280x720/autoscale/1/stripmeta/0|saveas/ZGVubnlsaWFuZy1odWFkb25nOnRlc3RfNDdfNTZfNTU1Lm1wNA=="
    //QString persistentOps = QString("avthumb/mp4/ab/160k/ar/44100/acodec/libfaac/r/30/vb/2200k/vcodec/libx264/s/1280x720/autoscale/1/stripmeta/0|saveas/");
    QString persistentOps = paraInfo.persistentOps;//QString("avthumb/mp4/vcodec/libx264|saveas/");
    persistentOps.append(strTargetAddress_MD5);


    std::string str = persistentOps.toStdString();
    putPolicy.persistentOps =  str.c_str();

    putPolicy.expires = paraInfo.expires;//7200

    std::string strI = paraInfo.persistentPipeline.toStdString();
    putPolicy.persistentPipeline =  strI.c_str();//"oeasy_test";//"denny_test";


    return Qiniu_RS_PutPolicy_Token(&putPolicy, mac);
}

void uploadVideoThread::onDealwithuploadVideoRequest(quint64 id,QString srcfilePath,QString DesfilePath,QString jpg1,QString jpg2,QString jpg3)
{
    /*if(id != m_nId)
    {
        return;
    }*/

    m_jpg1 = jpg1;
    m_jpg2 = jpg2;
    m_jpg3 = jpg3;

    QString strLog;
    if(srcfilePath.isEmpty() || srcfilePath.isNull())
    {
        strLog = QString("srcfilePath para is NULL!");
        logFile::printLog(strLog);
        return;
    }

    if(DesfilePath.isEmpty() || DesfilePath.isNull())
    {
        strLog = QString("DesfilePath para is NULL!");
        logFile::printLog(strLog);
        return;
    }

    m_curFilePath = srcfilePath;

    //QChar c
    int nLast = DesfilePath.lastIndexOf('/');
    int nCount = DesfilePath.length() - nLast - 1;
    QString fileName = DesfilePath.right(nCount);
    m_fileName = fileName;

    //"123456.jpg";//(const char*)(fileName.constData());//"1.jpg";
    //"D:/work/AlarmProxy/bin/debug/snapshot/123456.jpg";
    //"D:/work/AlarmProxy/bin/debug/snapshot/123456.jpg";//(const char*)(filePath.toUtf8().data());//"d:\\1.jpg";

    std::string str = fileName.toStdString();
    const char* uploadFileName = str.c_str();

    std::string str1 = srcfilePath.toStdString();
    const char* pLocalFilePath = str1.c_str();


    /*得到uploadKey*/
    //"dennyliang";//;//"test"//(const char*)(m_QinniubucketName.toLatin1().data());
    //"dennyliang-huadong";//"dennyliang-huabei";//"dennyliang-huadong";
    std::string str2 = paraInfo.bucket.toStdString();
    const char* bucketName = str2.c_str();
    const char* uploadtoken = upLoadToken(bucketName, &m_QinniuMac);

    m_uploadtoken = QString(uploadtoken);

    strLog.sprintf("**********************Get New uploadtoken=%s!",uploadtoken);
    logFile::printLog(strLog);

    Qiniu_Io_PutExtra extra;
    memset(&extra, 0, sizeof(extra));
    //extra.mimeType = ""


    strLog.sprintf("###########################upload video start:%s.",uploadFileName);
    logFile::printLog(strLog);

    //strLog.sprintf("**********************Qiniu_Io_PutFile::pLocalFilePath=%s!",pLocalFilePath);
    //logFile::printLog(strLog);


    Qiniu_Io_PutRet putRet;
    Qiniu_Error error = Qiniu_Io_PutFile(&m_QinniuClient, &putRet, m_uploadtoken.toStdString().c_str(), uploadFileName, pLocalFilePath, NULL);
    if (200 != error.code)
    {
        //printf("Upload File %s To %s:%s error.\n", pLocalFilePath, bucketName,  uploadFileName);
        //printf("%s", error.message);
        strLog.sprintf("Upload video %s To %s:%s error.", pLocalFilePath, bucketName,  uploadFileName);
        logFile::printLog(strLog);
        strLog = QString("%1").arg(error.message);
        logFile::printLog(strLog);
    }
    else
    {
        //printf("Upload File %s To %s:%s success.\n", pLocalFilePath, bucketName,  uploadFileName);
        //printf("url: %s -- %s", putRet.hash, putRet.key);
        strLog.sprintf("Upload video %s To %s:%s success.\n", pLocalFilePath, bucketName,  uploadFileName);
        logFile::printLog(strLog);
        strLog.sprintf("url: %s -- %s", putRet.hash, putRet.key);
        logFile::printLog(strLog);

        QFile::remove(m_curFilePath);
    }

    Qiniu_Free((void*)uploadtoken);

    //QFile::remove(m_jpg1);
    //QFile::remove(m_jpg2);
    //QFile::remove(m_jpg3);

    //emit sigVideoWorkFinish(m_nId);
}
